{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell #-}

module Repositorium where


import Control.Monad.State
import Control.Monad.Reader
import System.Environment
import Customer
import Haircut
import PerformedHaircut

import Data.Acid
import Data.SafeCopy
import Data.Typeable

data Repositorium = MkRepositorium [Haircut] [PerformedHaircut] [Customer]
        deriving (Show, Typeable)
$(deriveSafeCopy 0 'base ''Repositorium)


emptyRepositorium :: Repositorium
emptyRepositorium = MkRepositorium [] [] []


-------------- HAIRCUTS -------------------

addNewHaircut :: Haircut -> Update Repositorium ()
addNewHaircut hc = do
                        MkRepositorium hcs perfhc customers <- runQuery $ ask
                        put (MkRepositorium (hc:hcs) perfhc customers)

getAllHaircuts :: Query Repositorium [Haircut]
getAllHaircuts = do MkRepositorium hcs perfhc customers <- ask
                    return hcs

---------- CUSTOMERS --------------

getAllCustomers :: Query Repositorium [Customer]
getAllCustomers = do MkRepositorium hcs perfhc customers <- ask
                     return customers
                     
addNewCustomer :: Customer -> Update Repositorium ()
addNewCustomer customer = do
                        MkRepositorium hcs perfhc customers <- runQuery $ ask
                        put (MkRepositorium hcs perfhc (customer:customers))
                    
updateCustomerName :: Customer -> CustomerName -> Update Repositorium ()
updateCustomerName ctm newName = do
    MkRepositorium hcs perfhc customers <- runQuery $ ask
    put (MkRepositorium hcs perfhc (changeCustomerName ctm newName customers)) 
    
    
updateCustomer :: Customer -> Update Repositorium ()
updateCustomer ctm = do
    MkRepositorium hcs perfhc customers <- runQuery $ ask
    put (MkRepositorium hcs perfhc (replaceCustomer ctm customers) )
    
 
replaceCustomer :: Customer -> [Customer] -> [Customer]   
replaceCustomer ctm (c:cs) = if ((getCustomerName ctm) == (getCustomerName c))
                                 then (ctm:cs)
                                 else c : (replaceCustomer ctm cs) 

changeCustomerName customer newName (c:cs) = if ((getCustomerName customer) == (getCustomerName c))
                                               then (setCustomerName c newName): cs
                                               else c : (changeCustomerName customer newName cs)
        
------------  PERFORMED HAIRCUTS -------------

getAllPerformedHc :: Query Repositorium [PerformedHaircut]
getAllPerformedHc = do MkRepositorium hcs perfhc customers <- ask
                       return perfhc


------------------------------------------------------

$(makeAcidic ''Repositorium ['addNewHaircut, 'getAllHaircuts, 
  'getAllCustomers, 'getAllPerformedHc, 'addNewCustomer, 'updateCustomer, 'updateCustomerName])
